#!/bin/sh
set -e

BINDIR=`dirname $0`
if [ "$JAVA_HOME" = "" ]; then
	JAVA=java
else
	JAVA="$JAVA_HOME/bin/java"
fi
TVNC_JAVADIR=@CMAKE_INSTALL_FULL_JAVADIR@
if [ -d $BINDIR/../java ]; then
	TVNC_JAVADIR=$BINDIR/../java
fi

# Attempt to figure out where libjawt.so lives
ARCH=@CPU_TYPE@
if [ "$ARCH" = "x86_64" ]; then
	ARCH=amd64
fi

if [ "$JAVA_HOME" != "" ]; then
	if [ -f "$JAVA_HOME/lib/$ARCH/libjawt.so" ]; then
		JAWT_PATH=$JAVA_HOME/lib/$ARCH
	elif [ -f "$JAVA_HOME/lib/libjawt.so" ]; then
		JAWT_PATH=$JAVA_HOME/lib
	fi
fi

if [ "$JAWT_PATH" = "" ]; then
	# This should work with OpenJDK or Oracle Java 7 and later.
	_TMP=`java -XshowSettings:properties -version 2>&1 | grep sun.boot.library.path | sed s/.*=\ //g`
	if [ -f "$_TMP/libjawt.so" ]; then
		JAWT_PATH=$_TMP
	fi
fi

if [ "$JAWT_PATH" = "" ]; then
	# This may be required for IBM Java
	_TMP=`java -XshowSettings:properties -version 2>&1 | grep java.home | sed s/.*=\ //g`
	if [ -f "$_TMP/lib/$ARCH/libjawt.so" ]; then
		JAWT_PATH=$_TMP/lib/$ARCH
	fi
fi

if [ "$JAWT_PATH" = "" ]; then
	# Maybe we're using Java 6 or earlier.  Try some common paths.
	for dir in /usr/lib64/jvm/jre /usr/lib/jvm/jre /usr/lib/jvm/java-6-openjdk/jre /usr/java/default/jre /usr/java/latest/jre; do
		if [ -f $dir/lib/$ARCH/libjawt.so ]; then
			JAWT_PATH=$dir/lib/$ARCH
			break
		fi
	done
fi

if [ "$JAWT_PATH" = "" ]; then
	echo WARNING: Could not find libjawt.so.  Some features may not work properly.
else
	echo libjawt.so path: $JAWT_PATH
	LD_LIBRARY_PATH=$JAWT_PATH:$LD_LIBRARY_PATH
	export LD_LIBRARY_PATH
fi
if [ "@BITS@" = "32" ]; then
	exec $JAVA -server -d@BITS@ -Djava.library.path=$TVNC_JAVADIR -jar $TVNC_JAVADIR/VncViewer.jar ${1+"$@"}
else
	exec $JAVA -server -Djava.library.path=$TVNC_JAVADIR -jar $TVNC_JAVADIR/VncViewer.jar ${1+"$@"}
fi
